package com.carnation.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carnation.service.FileService;
import com.carnation.service.Ftp;
import com.carnation.service.impl.FTPServerImpl;
import com.carnation.service.impl.FileServiceImpl;
import com.carnation.service.impl.SFTPServerImpl;
import com.carnation.utils.Json;
import com.carnation.utils.MenuFileUtril;
import com.google.gson.Gson;

public class UploadFTPServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{
		String localfake = httpServletRequest.getParameter("localpath");
		String remotefake = httpServletRequest.getParameter("remotepath");
		String filename = httpServletRequest.getParameter("filename");
		MenuFileUtril menuFileUtril = new MenuFileUtril();
		Ftp ftp = null;
		if(menuFileUtril.getFTPProtocol().toLowerCase().equals("ftp")){
			ftp = new FTPServerImpl();
		}
		else if(menuFileUtril.getFTPProtocol().toLowerCase().equals("sftp")){
			ftp = new SFTPServerImpl();
		}
		else{
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.getWriter().write("未知协议");
			httpServletResponse.getWriter().close();
			return ;
		}
		FileService fileService = new FileServiceImpl();
		String msg = null;
		try {
			String rRealPath = ftp.getPath(remotefake);
			String lRealPath = fileService.getRealPath(localfake);
			File file = new File(lRealPath, filename);
			if(!file.exists() || !file.isFile()){
				msg = "本地文件不存在";
			}
			else{
				ftp.uploadFile(rRealPath,file.getAbsolutePath(), filename);
				msg = "上传成功";
			}
			Json json = new Json();
			json.setMsg(msg);
			Gson gson = new Gson();
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.getWriter().write(gson.toJson(json));
			httpServletResponse.getWriter().close();
		} catch (Exception e) {
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.getWriter().write(e.getMessage());
			httpServletResponse.getWriter().close();
			return ;
		}
	}
}
